package com.example.demo.utils;

import com.example.demo.entity.MyException;
import com.example.demo.entity.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

@RestControllerAdvice
@Slf4j
public class MyExceptionHandler {
    /**
     * 功能描述: 全局异常处理
     *
     * @param ex 异常
     * @return 异常响应结果
     * @date 2018/9/20 14:48
     */
    @ExceptionHandler(Exception.class)
    public Map<Object, Object> resolveException(Exception ex) {
        Map<Object, Object> res;
        if (ex instanceof MyException) {
            MyException myException = (MyException) ex;
            if (myException.getResultEnum() != null) {
                res = Waiter.error(myException.getResultEnum());
            } else {
                if (myException.getException() != null) {
                    ex = myException.getException();
                }
                res = Waiter.error(ResultEnum.ERROR);
            }
        } else {
            res = Waiter.error(ResultEnum.ERROR);
        }
        //打印异常信息
        logErrorInfo(ex);
        return res;
    }

    /**
     * 功能描述: 打错异常信息
     *
     * @param ex 异常
     * @date 2018/9/20 14:48
     */
    private static void logErrorInfo(Exception ex) {
        StackTraceElement s;
        if (ex.getStackTrace().length >= 1) {
            for (int i = 0; i < 1; i++) {
                s = ex.getStackTrace()[i];
                //打印抛出异常的类名、方法名、行数、异常信息
                log.error(s.getClassName() + " " + s.getMethodName() + " " + s.getLineNumber() + " " + ex.getMessage());
            }
        }
    }
}
